/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.to.aboomy.banner;

import ohos.agp.components.AttrSet;
import ohos.agp.components.Image;
import ohos.agp.components.element.Element;
import ohos.agp.utils.Color;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayAttributes;
import ohos.agp.window.service.DisplayManager;
import ohos.app.Context;
import ohos.app.dispatcher.TaskDispatcher;
import ohos.app.dispatcher.task.TaskPriority;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.IOException;
import java.util.Optional;

/**
 * Utils
 *
 * @since 2021-04-16
 */
public class Utils2 {
    private static Utils2 instance = null;

    /**
     * 初始化
     *
     * @return instance
     */
    public static synchronized Utils2 getInstance() {
        if (instance == null) {
            instance = new Utils2();
        }
        return instance;
    }

    /**
     * getScreenPiex
     *
     * @param context
     * @return DisplayAttributes
     * @noinspection checkstyle:WhitespaceAround
     */
    public DisplayAttributes getScreenPiex(Context context) {
        // 获取屏幕密度
        Optional<Display> display = DisplayManager.getInstance().getDefaultDisplay(context);
        DisplayAttributes displayAttributes = null;
        if (display.isPresent()) {
            displayAttributes = display.get().getAttributes();
        }
        return displayAttributes;
    }

    /**
     * dp2Px
     *
     * @param context
     * @param dp
     * @return float
     */
    public float dp2Px(Context context, float dp) {
        // 获取屏幕密度
        DisplayAttributes displayAttributes = getScreenPiex(context);
        return dp * displayAttributes.scalDensity;
    }

    /**
     * getAttrStringValue
     *
     * @param attrSet
     * @param key
     * @param defValue
     * @return String
     */
    public String getAttrStringValue(AttrSet attrSet, String key, String defValue) {
        if (attrSet.getAttr(key).isPresent()) {
            return attrSet.getAttr(key).get().getStringValue();
        } else {
            return defValue;
        }
    }

    /**
     * getAttrIntValue
     *
     * @param attrSet
     * @param key
     * @param defValue
     * @return int
     */
    public int getAttrIntValue(AttrSet attrSet, String key, int defValue) {
        if (attrSet.getAttr(key).isPresent()) {
            return attrSet.getAttr(key).get().getIntegerValue();
        } else {
            return defValue;
        }
    }

    /**
     * getAttrBoolValu
     *
     * @param attrSet
     * @param key
     * @param isDefValue
     * @return Boolean
     */
    public boolean getAttrBoolValue(AttrSet attrSet, String key, boolean isDefValue) {
        if (attrSet.getAttr(key).isPresent()) {
            return attrSet.getAttr(key).get().getBoolValue();
        } else {
            return isDefValue;
        }
    }

    /**
     * getAttrElementValue
     *
     * @param attrSet
     * @param key
     * @param defValue
     * @return Element
     */
    public Element getAttrElementValue(AttrSet attrSet, String key, Element defValue) {
        if (attrSet.getAttr(key).isPresent()) {
            return attrSet.getAttr(key).get().getElement();
        } else {
            return defValue;
        }
    }

    /**
     * getAttrColorValue
     *
     * @param attrSet
     * @param key
     * @param defValue
     * @return Color
     */
    public Color getAttrColorValue(AttrSet attrSet, String key, Color defValue) {
        if (attrSet.getAttr(key).isPresent()) {
            return attrSet.getAttr(key).get().getColorValue();
        } else {
            return defValue;
        }
    }

    /**
     * 从本地media文件夹创建PIXEMAP图片
     *
     * @param context
     * @param mediaId
     * @return PixelMap
     * @throws NotExistException
     * @throws WrongTypeException
     * @throws IOException
     */
    public PixelMap getPixelMapFromMedia(Context context, int mediaId)
            throws NotExistException, WrongTypeException, IOException {
        ImageSource.SourceOptions options = new ImageSource.SourceOptions();
        options.formatHint = "image/jpg";
        ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
        ResourceManager manager = context.getResourceManager();
        String path = manager.getMediaPath(mediaId);
        Resource resource = manager.getRawFileEntry(path).openRawFile();
        ImageSource source = ImageSource.create(resource, options);
        return source.createPixelmap(decodingOptions);
    }

    /**
     * 从网络加载图片
     *
     * @param context
     * @param image
     * @param imgurl
     */
    public void setBitmap(Context context, Image image, String imgurl) {
        TaskDispatcher refreshTask = context.createParallelTaskDispatcher("", TaskPriority.DEFAULT);
        refreshTask.syncDispatch(() -> {
            new BitmapLoaderTask(imgurl, new BitmapLoaderTask.Callback() {
                @Override
                public void result(PixelMap bitmap) {
                    image.setPixelMap(bitmap);
                    bitmap.release();
                }
            });
        });
    }
}
